package com.cms.recursoshumanos.component.base;

import com.cms.recursoshumanos.utilities.Tool;

import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.accessibility.AccessibleText;
import net.rim.device.api.ui.component.PasswordEditField;

public class CustomPasswordField extends PasswordEditField {
	private int highlightColor;
	
	public String repeatString(String character, int times) {
		String word = "";
		for(int i = 0; i < times; i++)
			word += character;
		
		return word;
	}
	
	public CustomPasswordField(String label, String initialValue, int maxNumChars, long style) { 
		this(label, initialValue, maxNumChars, style, Color.BLUE);
	}

	public CustomPasswordField(String label, String initialValue, int maxNumChars, long style, int highlight) { 
		super(label, initialValue, maxNumChars, style);
	
		highlightColor = highlight;
		this.setPadding(2, 2, 2, 2);
	}
	
	protected void drawFocus(Graphics graphics, boolean on) {
		XYRect contentRect = new XYRect();
		getFocusRect(contentRect);
		
		if(on) {
			AccessibleText text = getAccessibleContext().getAccessibleText();
			String textoSelect = text.getSelectionText();
			
			int caret = text.getCaretPosition();
			if(textoSelect.compareTo("") == 0) {
				graphics.setColor(highlightColor);
				graphics.fillRect(contentRect.x, contentRect.y, contentRect.width, contentRect.height);
				graphics.setColor(Color.WHITE);
				try {
					graphics.drawText("*", contentRect.x, contentRect.y, 0, contentRect.width);
				} catch (Exception e) {
					// Esta al final del texto...
				}
			} else {
				// Aqui el contentRect deberia ser el de la seleccion
				graphics.setColor(highlightColor);
				int x, width, height;
				int start = text.getSelectionStart();
				String textoX = Tool.getInstance().repeatString("*", textoSelect.length());
				if(caret > start) {
					width = getFont().getAdvance(textoX);
					height = getFont().getHeight();
					x = contentRect.x - width;
				} else {
					width = getFont().getAdvance(textoX);
					height = getFont().getHeight();
					x = contentRect.x;
				}
				graphics.fillRect(x, contentRect.y, width, height);
				graphics.setColor(Color.WHITE);
				try {
					graphics.drawText(textoX, x, contentRect.y, 0, width);
				} catch (Exception e) {
					// Esta al final del texto...
				}
			}
		}
	}
}
